﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowIcon(QIcon(":/logo/logo.ico"));
    QString window_title = TTT(APP_NAME);
    setWindowTitle(window_title);
    qDebug() << "BoardTestParameterConfig Runing Version:" << QCoreApplication::applicationVersion();
    qDebug() << "BoardTestParameterConfig CurrentThradId:" << QThread::currentThreadId();

    setupDisplayinterface();
    setupMainStates();
    setupSerialThread();
}

MainWindow::~MainWindow()
{
    m_serialThread.quit();
    m_serialThread.wait();
    delete ui;
}

void MainWindow::setupDisplayinterface()
{
    //添加界面
    my_maindesigner = new MainDesigner(this);
    my_systemsetting = SystemSetting::instance(this);;
    ui->stackedWidget->addWidget(my_maindesigner);
    ui->stackedWidget->addWidget(my_systemsetting);
    //添加左侧导航栏按钮
    btn_group.addButton(ui->tbtn_mainDesigner,0);
    btn_group.addButton(ui->tbtn_systemSet,1);
    // 设置默认选中的页面
    btn_group.button(0)->setChecked(true);
    ui->stackedWidget->setCurrentIndex(0);
    //信号连接
    connect(&btn_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked),
            ui->stackedWidget, &QStackedWidget::setCurrentIndex);
    connect(this,&MainWindow::sig_displayLog, my_maindesigner,&MainDesigner::slots_displayLog);
    connect(my_systemsetting, &SystemSetting::sig_changeSerial,this,
            [=](QString port_name,int baud_rate){
                emit sig_changeSerial(port_name,baud_rate);
                emit sig_serialOpen();
            });
}

void MainWindow::setupMainStates()
{
    // 创建状态栏
    //QStatusBar *bar = statusBar();
    statusBar()->setStyleSheet("QStatusBar { background-color: #f0f0f0; border-top: 1px solid #d0d0d0; }");

    //串口状态
    lab_serialState = new QLabel("串口状态:未打开",statusBar());
    lab_serialState->setStyleSheet("padding: 2px 8px; color: #606060;");
    this->statusBar()->addWidget(lab_serialState);

    // 添加弹簧，将右侧控件推到最右边
    QWidget *spacer = new QWidget(statusBar());
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    statusBar()->addWidget(spacer);
    // 创建消息标签（位于右侧）
    lab_tempMessage = new QLabel(statusBar());
    lab_tempMessage->setStyleSheet("color: #606060;");
    lab_tempMessage->setAlignment(Qt::AlignCenter);
    lab_tempMessage->setMinimumWidth(200);
    lab_tempMessage->hide();
    // 将消息标签作为永久部件添加到状态栏
    statusBar()->addPermanentWidget(lab_tempMessage);
    // 初始化定时器
    messageTimer.setSingleShot(true);
    connect(&messageTimer, &QTimer::timeout, this, &MainWindow::hideMessage);
}

void MainWindow::setupSerialThread()
{
    m_serialWork = new SerialService();
    m_serialWork->moveToThread(&m_serialThread);
    // 连接串口服务的信号
    connect(my_maindesigner,&MainDesigner::sig_serialWrite,m_serialWork,&SerialService::slots_SerialWriteData);

    connect(my_systemsetting, &SystemSetting::sig_changeTimeout,
            m_serialWork, &SerialService::slots_ReceiveTimeout);

    connect(m_serialWork, &SerialService::sig_SerialOpened,this,[this](const QString &port_name){
        if( lab_serialState) {
            QString msg = QString("当前串口%1 状态:已打开").arg(port_name);
            lab_serialState->setStyleSheet("padding: 2px 8px;color: green;");
            lab_serialState->setText(msg);
            my_systemsetting->setSerialOpened(true);
        }
    });
    connect(m_serialWork, &SerialService::sig_SerialClosed,this,[this](){
        if( lab_serialState) {
            lab_serialState->setStyleSheet("padding: 2px 8px;color: #606060;");
            lab_serialState->setText("串口状态:未打开");
            my_systemsetting->setSerialOpened(false);
        }
    });
    connect(m_serialWork, &SerialService::sig_SerialReceiveData,my_maindesigner,&MainDesigner::slots_serialRead);
    connect(m_serialWork,SIGNAL(SerialService::sig_serialWriteData),my_maindesigner,SLOT(MainDesigner::slots_displayLog));
    connect(m_serialWork,&SerialService::sig_SerialerrorOccurred,this,[=](const QString error_msg){
                showTemporaryMessage(error_msg,3000,COLOR_ERROR);
            });
    connect(&m_serialThread, &QThread::finished, m_serialWork, &QObject::deleteLater);
    connect(this,&MainWindow::sig_changeSerial,m_serialWork,&SerialService::slots_UpdateSerial);
    connect(this,&MainWindow::sig_serialOpen,m_serialWork,&SerialService::slots_OpenSerialPort);
    connect(this,&MainWindow::sig_serialClose,m_serialWork,&SerialService::slots_CloseSerialPort);
    // 启动线程
    m_serialThread.start();
    QString port_name = my_systemsetting->serialName();
    QSerialPort::BaudRate baud_rate = my_systemsetting->serialBaud();
    m_serialWork->slots_UpdateSerial(port_name,baud_rate);
    m_serialWork->slots_OpenSerialPort();
}

void MainWindow::showTemporaryMessage(const QString &message, int timeout, const QString &color)
{
    if (!fadeAnimation) {
         fadeAnimation = new QPropertyAnimation(lab_tempMessage, "windowOpacity", this);
    }
    // 如果当前有消息正在显示，加入队列
    if (lab_tempMessage->isVisible() &&  fadeAnimation) {
        qDebug() << __FUNCTION__ << "message:" << message << "timeout:"<< timeout<<"lab_tempMessage->isVisible():"<<lab_tempMessage->isVisible()
                 << "fadeAnimation:" << fadeAnimation->state();
        messageQueue.enqueue({message, timeout, color});
        return;
    }
    // 设置消息内容和样式
    lab_tempMessage->setText(message);
    lab_tempMessage->setStyleSheet(QString(
                                    "QLabel {"
                                    "  color: %1;"
                                    "  padding: 2px 8px;"
                                    "  border-radius: 3px;"
                                    "  margin-right: 5px;"
                                    "}"
                                    ).arg(color));

    // 显示消息（带淡入动画）
    fadeAnimation = new QPropertyAnimation(lab_tempMessage, "windowOpacity", this);
    fadeAnimation->setDuration(300);
    fadeAnimation->setStartValue(0);
    fadeAnimation->setEndValue(1);
    connect(fadeAnimation, &QPropertyAnimation::finished, this, [this]() {
        delete fadeAnimation;
        fadeAnimation = nullptr;
    });
    fadeAnimation->start();
    lab_tempMessage->show();
    // 设置定时器
    messageTimer.stop();
    messageTimer.setInterval(timeout);
    messageTimer.start();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton button = \
        (QMessageBox::StandardButton)QMessageBox::question(this,"LeftNavigationDemo","确认退出", \
            QMessageBox::StandardButton::Yes,QMessageBox::StandardButton::No);
    if( QMessageBox::StandardButton::Yes == button ) {
        m_serialThread.quit();
        m_serialThread.wait();
        event->accept();    //默认情况下接收关闭信号，关闭窗体
    }
    else {
        event->ignore();    //忽略关闭信号,组织窗体关闭
    }
}

void MainWindow::hideMessage()
{
    // 淡出动画
    fadeAnimation = new QPropertyAnimation(lab_tempMessage, "windowOpacity", this);
    fadeAnimation->setDuration(300);
    fadeAnimation->setStartValue(1);
    fadeAnimation->setEndValue(0);
    connect(fadeAnimation, &QPropertyAnimation::finished, this, [this]() {
        lab_tempMessage->hide();
        delete fadeAnimation;
        fadeAnimation = nullptr;
        // 显示队列中的下一条消息
        if (!messageQueue.isEmpty()) {
            auto next = messageQueue.dequeue();
            showTemporaryMessage(next.message, next.timeout, next.color);
        }
    });
    fadeAnimation->start();
}

